package com.alawn.web.security.controller;

import java.util.ArrayList;
import java.util.List;

import org.ocpsoft.rewrite.annotation.Join;
import org.primefaces.model.DualListModel;
import org.primefaces.model.LazyDataModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.alawn.framework.core.web.faces.annotation.MessageRequired;
import com.alawn.framework.core.web.faces.annotation.MessageType;
import com.alawn.framework.core.web.faces.controller.FacesController;
import com.alawn.framework.services.security.Role;
import com.alawn.framework.services.security.User;
import com.alawn.security.service.RoleService;
import com.alawn.security.service.UserService;
import com.alawn.web.security.model.UserDataModel;

@Controller("/views/security/user.faces")
@Join(path = "/security/user", to = "/views/security/user.faces")
public class UserController extends FacesController {

	@Autowired
	private UserService userService;

	@Autowired
	private RoleService roleService;

	@Override
	public void initPage() {
		putViewScope("roleModel", roleModel(null));
		putViewScope("selectedUsers", new User[0]);
	}

	public LazyDataModel<User> getDataModel() {
		return UserDataModel.getInstance();
	}

	@MessageRequired(type = MessageType.SAVE)
	public void save() {
		User user = (User) getViewScope("user");
		userService.save(user);
	}

	public void edit() {
		User[] users = (User[]) getViewScope("selectedUsers");
		User user = users.length > 0 ? users[0] : null;
		putViewScope("roleModel", roleModel(user.getUsername()));
		putViewScope("user", user);
	}

	@MessageRequired(type = MessageType.DELETE)
	public void delete() {
		User[] users = (User[]) getViewScope("selectedUsers");
		List<Long> ids = new ArrayList<>();
		for (User user : users) {
			ids.add(user.getId());
		}
		userService.removeByIds(ids);
	}

	public DualListModel<Role> roleModel(String username) {
		List<Role> rolesSource = roleService.list();
		List<Role> rolesTarget = userService.findRolesByUserName(username);
		return new DualListModel<Role>(rolesSource, rolesTarget);
	}

}
